package com.maserb.monitor.service.common.impl;

import com.maserb.monitor.service.JwReport.JwFileInfoService;
import com.maserb.monitor.service.common.FileService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Value("${monitor.uploadDir}")
    private String uploadDir;

    @Autowired
    JwFileInfoService infoService;

    @Override
    public String getUploadDir() {
        return uploadDir;
    }

    @Override
    public String upload(MultipartFile multipartFile) throws IOException {
        String dirPath = this.getUploadDir() + "image\\";
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String splitDirPath = sdf.format(date);
        String relativeFilename = FilenameUtils.concat(dirPath, splitDirPath);
        File dir = new File(relativeFilename);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        splitDirPath = "image/" + splitDirPath;
        String extension = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
        String filename = UUID.randomUUID() + "." + extension;
        String realFilename = FilenameUtils.concat(splitDirPath, filename);
        File serverFile = new File(FilenameUtils.concat(relativeFilename, filename));
        multipartFile.transferTo(serverFile);
        return realFilename.replaceAll("\\\\", "/");
    }

    @Override
    public String uploadHead(MultipartFile multipartFile,String schoolId,String studentId) throws IOException {
        String dirPath = this.getUploadDir() + "\\";
        String relativeFilename = FilenameUtils.concat(dirPath, schoolId);
        File dir = new File(relativeFilename);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String extension = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
        if(StringUtils.isEmptyOrWhitespace(studentId)){
            studentId = UUID.randomUUID() +"";
        }
        String filename = studentId + "." + extension;
        String realFilename = FilenameUtils.concat(schoolId, filename);
        File serverFile = new File(FilenameUtils.concat(relativeFilename, filename));
        if (serverFile.exists()) {
            serverFile.delete();
            serverFile = new File(FilenameUtils.concat(relativeFilename, filename));
        }
        multipartFile.transferTo(serverFile);
        return realFilename.replaceAll("\\\\", "/");
    }

    @Override
    public ResponseEntity<byte[]> downloadImage(String relativePath) throws Exception {
        String filename = FilenameUtils.concat(getUploadDir(), relativePath);
        File file = new File(filename);
        HttpHeaders headers = new HttpHeaders();
//        //下载显示的文件名，解决中文名称乱码问题
//        String downloadFielName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
//        //通知浏览器以attachment（下载方式）打开图片
//        headers.setContentDispositionFormData("attachment", downloadFielName);
        headers.setContentType(MediaType.IMAGE_JPEG);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }

    @Override
    public ResponseEntity<byte[]> downloadFile(String relativePath) throws Exception {
        String filename = FilenameUtils.concat(getUploadDir(), relativePath);
        File file = new File(filename);
        HttpHeaders headers = new HttpHeaders();
//        //下载显示的文件名，解决中文名称乱码问题
        /*String downloadFielName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
        headers.setContentDispositionFormData("attachment", downloadFielName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);*/
        headers.setContentType(MediaType.parseMediaType("audio/mpeg"));
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);

    }

    @Override
    public void downloadFileByUrl(HttpServletRequest request, HttpServletResponse response, String relativePath) throws Exception {
        String filename = FilenameUtils.concat(getUploadDir(), relativePath);
        File file = new File(filename);
        FileInputStream in = new FileInputStream(file);
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment; filename=" + UUID.randomUUID().toString() + ".xls");
        response.setContentLength((int)file.length());
        ServletOutputStream out = response.getOutputStream();
        byte[] b = null;
        while (in.available() > 0) {
            if (in.available() > 10240) {
                b = new byte[10240];
            } else {
                b = new byte[in.available()];
            }
            in.read(b, 0, b.length);
            out.write(b, 0, b.length);
        }
        in.close();
        out.flush();
        out.close();
    }

    @Override
    public void downloadAudio(String relativePath, HttpServletResponse response) throws Exception {
        String filename = FilenameUtils.concat(getUploadDir(), relativePath);
        File file = new File(filename);
        FileInputStream in = new FileInputStream(file);
        response.setContentType("audio/mpeg");
        response.setContentLength((int)file.length());
        ServletOutputStream out = response.getOutputStream();
        byte[] b = null;
        while (in.available() > 0) {
            if (in.available() > 10240) {
                b = new byte[10240];
            } else {
                b = new byte[in.available()];
            }
            in.read(b, 0, b.length);
            out.write(b, 0, b.length);
        }
        in.close();
        out.flush();
        out.close();
    }
}
